package com.proback.service.impl;

import com.proback.dto.BookDataAddRequest;
import com.proback.dto.BookDataUpdateRequest;
import com.proback.entity.BookData;
import com.proback.entity.User;
import com.proback.repository.BookDataRepository;
import com.proback.repository.UserRepository;
import com.proback.service.BookDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Year;
import java.time.YearMonth;
import java.util.List;

@Service
public class BookDataServiceImpl implements BookDataService {

    @Autowired
    private BookDataRepository repository;

    @Autowired
    private UserRepository userRepository;

    @Override
    public void add(BookDataAddRequest request) {
        User user = userRepository.findById(request.getUserId())
                .orElseThrow(() -> new RuntimeException("用户不存在"));

        BookData data = new BookData(null, request.getType(), request.getBookDate(),
                request.getCategory(), request.getPrice(), request.getRemark(), user, request.getSource());

        repository.save(data);
    }

    @Override
    public List<BookData> listByUserId(Integer userId) {
        return repository.findByUserId(userId);
    }

    @Override
    public void update(BookDataUpdateRequest request) {
        User user = userRepository.findById(request.getUserId())
                .orElseThrow(() -> new RuntimeException("用户不存在"));

        BookData data = new BookData(request.getId(), request.getType(), request.getBookDate(),
                request.getCategory(), request.getPrice(), request.getRemark(), user, request.getSource());

        repository.save(data);
    }

    @Override
    public void delete(Integer id) {
        repository.deleteById(id);
    }

    @Override
    public List<BookData> listByUserIdAndYear(Integer userId, Year year) {
        return repository.findByUserIdAndBookDateYear(userId, year.getValue());
    }

    @Override
    public List<BookData> listByUserIdAndYearMonth(Integer userId, YearMonth yearMonth) {
        return repository.findByUserIdAndBookDateYearAndBookDateMonth(userId, yearMonth.getYear(), yearMonth.getMonthValue());
    }
}
